package com.example.demopay.client;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;

public class Client {
    private static CloseableHttpClient httpClient=null;

    //初始化
    public static CloseableHttpClient httpClient() throws IOException {
        InputStream is=new FileInputStream("E:\\Key\\apiclient_key.pem");
        PrivateKey privateKey= PemUtil.loadPrivateKey(is);
        is.close();
        //加载平台证书
        AutoUpdateCertificatesVerifier verifier=new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials("1558950191",
                        new PrivateKeySigner("34345964330B66427E0D3D28826C4993C77E631F",privateKey)),
                "UDuLFDcmy5Eb6o0nTNZdu6ek4DDh4K8B".getBytes("UTF-8")
        );
        //初始化httpClient
        return httpClient= WechatPayHttpClientBuilder.create()
                .withMerchant("1558950191","34345964330B66427E0D3D28826C4993C77E631F",privateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
    }
    public static void after(CloseableHttpClient httpClient) throws IOException {
        httpClient.close();
    }
}
